package com.weixin.paleituo.activity;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.weixin.paleituo.R;
import com.weixin.paleituo.adapter.ClassifyGoodsRecycleAdapter;
import com.weixin.paleituo.application.BaseApplication;
import com.weixin.paleituo.base.BaseActivity;
import com.weixin.paleituo.bean.Brands;
import com.weixin.paleituo.bean.ClassifyGoodsListBean;
import com.weixin.paleituo.bean.Goods;
import com.weixin.paleituo.bean.StatusCode;
import com.weixin.paleituo.contans.Contans;
import com.weixin.paleituo.eventbus.SelectBrandEvent;
import com.weixin.paleituo.http.HttpUtil;
import com.weixin.paleituo.http.ProgressSubscriber;
import com.weixin.paleituo.rxjava.ApiUtils;
import com.weixin.paleituo.util.LoadingDialogUtils;
import com.weixin.paleituo.util.StringUtils;
import com.weixin.paleituo.util.ToastUtils;
import com.weixin.paleituo.util.UIUtils;
import com.weixin.paleituo.view.BrandSelectPopuWindow;
import com.weixin.paleituo.view.LoadingPager;
import com.weixin.paleituo.view.YRecycleview;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class ClassifyGoodsListActivity extends BaseActivity {


    @BindView(R.id.iv_back_activity_class_goods_list)
    ImageView mIvBackActivityClassGoodsList;
    @BindView(R.id.iv_cart_activity_class_goods_list)
    ImageView mIvCartActivityClassGoodsList;
    @BindView(R.id.rl_search_root_activity_class_goods_list)
    RelativeLayout mRlSearchRootActivityClassGoodsList;
    @BindView(R.id.yrecycleview_activity_classify_list)
    YRecycleview mYrecycleviewActivityClassifyList;
    @BindView(R.id.tv_sales_activity_classify_goods_list)
    TextView mTvSalesActivityClassifyGoodsList;
    @BindView(R.id.tv_price_ll_pricatroot_activity_classify_goods_list)
    TextView mTvPriceLlPricatrootActivityClassifyGoodsList;
    @BindView(R.id.iv_price_ll_pricatroot_activity_classify_goods_list)
    ImageView mIvPriceLlPricatrootActivityClassifyGoodsList;
    @BindView(R.id.ll_pricatroot_activity_classify_goods_list)
    LinearLayout mLlPricatrootActivityClassifyGoodsList;
    @BindView(R.id.tv_brand_activity_classify_goods_list)
    TextView mTvBrandActivityClassifyGoodsList;
    @BindView(R.id.iv_brand_activity_classify_goods_list)
    ImageView mIvBrandActivityClassifyGoodsList;
    @BindView(R.id.ll_brand_activity_classify_goods_list)
    LinearLayout mLlBrandActivityClassifyGoodsList;
    private BrandSelectPopuWindow mBrandSelectPopuWindow;
    @BindView(R.id.rl_bar_root_activity_classify_goods_list)
    LinearLayout mRelativeLayoutBarRoot;
    @BindView(R.id.viewline2_activity_classify_goods_list)
    View viewLine2;
    @BindView(R.id.tv_house_direct_activity_classify_goods_list)
    TextView mTvhouseDirect;
    private int currentPosion=1;
    private String salesSort="";
    private String priceSort="";
    private String specialSalesType="";
    private String goodsName="";
    private LoadingPager mLoadingPager;
    private List<Integer> selectBrandList=new ArrayList<>();
    private List<Goods> mGoodsList=new ArrayList<>();
    private List<Brands> mBrandsList=new ArrayList<>();
    private ClassifyGoodsRecycleAdapter mClassifyGoodsRecycleAdapter;
    private Dialog mLoadingDialog;
    private String mClassId;
    private RelativeLayout mRlEmpty;
    @BindView(R.id.tv_search_good_name_activity_classify_goods_list)
    TextView mTvSearchGoodsName;

    @Override
    protected void initView() {
        mLoadingPager = new LoadingPager(this) {
            @Override
            protected void close() {
                finish();
            }
           // rl_searchcontent_root_activity_classify_goods_list

            @Override
            protected View createSuccessView() {
                return UIUtils.inflate(ClassifyGoodsListActivity.this,R.layout.activity_classify_goods_list);
                //iv_cart_activity_class_goods_list
            }
            @Override
            protected void reLoading() {
                retry();

            }
        };


      //  setContentView(R.layout.activity_classify_goods_list);

        mRlEmpty = mLoadingPager.findViewById(R.id.rl_empty_activity_classify_goods_list);
        setContentView(mLoadingPager);
    }




    private void showData(Boolean isData){

        if (isData){
            mRlEmpty.setVisibility(View.GONE);
            mYrecycleviewActivityClassifyList.setVisibility(View.VISIBLE);
        }else {
            mRlEmpty.setVisibility(View.VISIBLE);
            mYrecycleviewActivityClassifyList.setVisibility(View.GONE);
        }

    }

    /**
     * 重新加载
     */
    private void retry() {
        Observable<StatusCode<ClassifyGoodsListBean>> classifyGoodsLsitObservable = ApiUtils.getApi().getClassifyGoodsLsit(mClassId, selectBrandList, salesSort, priceSort, BaseApplication.getToken(), Contans.rows, currentPosion,BaseApplication.getUserId(),specialSalesType,goodsName);
        HttpUtil.getInstance().toSubscribe(classifyGoodsLsitObservable, new ProgressSubscriber<ClassifyGoodsListBean>(this) {
            @Override
            protected void _onNext(StatusCode<ClassifyGoodsListBean> classifyGoodsListBeanStatusCode) {

                ClassifyGoodsListBean data = classifyGoodsListBeanStatusCode.getData();

                if (classifyGoodsListBeanStatusCode.isFlag()&&data!=null){

                    List<Brands> brands = data.getBrands();
                    List<Goods> goods = data.getGoods();
                    if (goods!=null &&goods.size()>0){
                        showData( true);

                        mLoadingPager.showPagerView(Contans.STATE_SUCCEED);
                        mGoodsList.clear();
                        mGoodsList.addAll(goods);
                        mClassifyGoodsRecycleAdapter.notifyDataSetChanged();
                    }else {
                        mLoadingPager.showPagerView(Contans.STATE_EMPTY);
                    }

                    if (brands!=null &&brands.size()>0){
                        mBrandsList.clear();
                        mBrandsList.addAll(brands);
                    }
                }else {
                    mLoadingPager.showPagerView(Contans.STATE_EMPTY);
                }
            }

            @Override
            protected void _onError(String message) {
                mLoadingPager.showPagerView(Contans.STATE_ERROR);
                ToastUtils.makeText(message);

            }
        },"",lifecycleSubject,false,true);


    }

    public static void startActivity(Context context,String classId,String goodsName) {

        Intent intent = new Intent(context, ClassifyGoodsListActivity.class);
        intent.putExtra(Contans.INTENT_DATA,classId);
        intent.putExtra(Contans.INTENT_EXTRA,goodsName);
        context.startActivity(intent);

    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        mClassId = intent.getStringExtra(Contans.INTENT_DATA);
        goodsName=intent.getStringExtra(Contans.INTENT_EXTRA);
        mIvPriceLlPricatrootActivityClassifyGoodsList.setImageResource(R.mipmap.direction_default);
        mTvPriceLlPricatrootActivityClassifyGoodsList.setTextColor(UIUtils.getColor(R.color.c_ff383838));
        mTvBrandActivityClassifyGoodsList.setTextColor(UIUtils.getColor(R.color.c_ff383838));
        mIvBrandActivityClassifyGoodsList.setImageResource(R.mipmap.down_one);

        mTvhouseDirect.setTextColor(UIUtils.getColor(R.color.c_383838));
        mTvSalesActivityClassifyGoodsList.setTextColor(UIUtils.getColor(R.color.c_383838));

        mLoadingPager.showPagerView(Contans.STATE_LOADING);

        if (!StringUtils.isEmpty(goodsName)){
            mTvSearchGoodsName.setText(goodsName);
        }else {
            mTvSearchGoodsName.setText("请输入商品名称");
        }
        currentPosion=1;

        retry();
    }
    @Override
    protected void initData() {
        super.initData();
        currentPosion=1;
        Intent intent = getIntent();
        mClassId = intent.getStringExtra(Contans.INTENT_DATA);
        goodsName=intent.getStringExtra(Contans.INTENT_EXTRA);

        if (!StringUtils.isEmpty(goodsName)){
            mTvSearchGoodsName.setText(goodsName);
        }else {
            mTvSearchGoodsName.setText("请输入商品名称");
        }

        EventBus.getDefault().register(this);
        mClassifyGoodsRecycleAdapter = new ClassifyGoodsRecycleAdapter(this, mGoodsList);
        //设置布局管理器
        mYrecycleviewActivityClassifyList.setLayoutManager(new LinearLayoutManager(this));
        //设置adapter
        mYrecycleviewActivityClassifyList.setAdapter(mClassifyGoodsRecycleAdapter);
        //设置Item增加、移除动画
        mYrecycleviewActivityClassifyList.setItemAnimator(new DefaultItemAnimator());

        mIvPriceLlPricatrootActivityClassifyGoodsList.setImageResource(R.mipmap.direction_default);
        mTvPriceLlPricatrootActivityClassifyGoodsList.setTextColor(UIUtils.getColor(R.color.c_ff383838));
        mTvBrandActivityClassifyGoodsList.setTextColor(UIUtils.getColor(R.color.c_ff383838));
        mIvBrandActivityClassifyGoodsList.setImageResource(R.mipmap.down_one);

        retry();

        mYrecycleviewActivityClassifyList.setRefreshAndLoadMoreListener(new YRecycleview.OnRefreshAndLoadMoreListener() {
            @Override
            public void onRefresh() {

                Observable<StatusCode<ClassifyGoodsListBean>> classifyGoodsLsitObservable = ApiUtils.getApi().getClassifyGoodsLsit(mClassId, selectBrandList, salesSort, priceSort, BaseApplication.getToken(), Contans.rows, 1,BaseApplication.getUserId(),specialSalesType,goodsName);
                HttpUtil.getInstance().toSubscribe(classifyGoodsLsitObservable, new ProgressSubscriber<ClassifyGoodsListBean>(ClassifyGoodsListActivity.this) {
                    @Override
                    protected void _onNext(StatusCode<ClassifyGoodsListBean> classifyGoodsListBeanStatusCode) {
                        mYrecycleviewActivityClassifyList.setReFreshComplete();
                        ClassifyGoodsListBean data = classifyGoodsListBeanStatusCode.getData();
                        if (classifyGoodsListBeanStatusCode.isFlag()&&data!=null){
                            ToastUtils.makeText("刷新成功");
                            List<Brands> brands = data.getBrands();
                            List<Goods> goods = data.getGoods();
                            if (goods!=null &&goods.size()>0){
                                currentPosion=1;
                                mGoodsList.clear();
                                mGoodsList.addAll(goods);
                                mClassifyGoodsRecycleAdapter.notifyDataSetChanged();
                            }
                            if (brands!=null &&brands.size()>0){
                                mBrandsList.clear();
                                mBrandsList.addAll(brands);
                            }
                        }else {

                        }
                    }

                    @Override
                    protected void _onError(String message) {
                        mYrecycleviewActivityClassifyList.setReFreshComplete();
                        ToastUtils.makeText(message);

                    }
                },"",lifecycleSubject,false,true);

            }

            @Override
            public void onLoadMore() {

                Observable<StatusCode<ClassifyGoodsListBean>> classifyGoodsLsitObservable = ApiUtils.getApi().getClassifyGoodsLsit(mClassId, selectBrandList, salesSort, priceSort, BaseApplication.getToken(), Contans.rows, currentPosion+1,BaseApplication.getUserId(),specialSalesType,goodsName);
                HttpUtil.getInstance().toSubscribe(classifyGoodsLsitObservable, new ProgressSubscriber<ClassifyGoodsListBean>(ClassifyGoodsListActivity.this) {
                    @Override
                    protected void _onNext(StatusCode<ClassifyGoodsListBean> classifyGoodsListBeanStatusCode) {
                        mYrecycleviewActivityClassifyList.setloadMoreComplete();
                        ClassifyGoodsListBean data = classifyGoodsListBeanStatusCode.getData();
                        if (classifyGoodsListBeanStatusCode.isFlag()&&data!=null&&data.getBrands()!=null&&data.getBrands().size()>0&&data.getGoods()!=null&&data.getGoods().size()>0){
                            ToastUtils.makeText("加载更多完成");
                            List<Brands> brands = data.getBrands();
                            List<Goods> goods = data.getGoods();
                            if (goods!=null &&goods.size()>0){

                                currentPosion+=1;
                                mGoodsList.addAll(goods);
                                mClassifyGoodsRecycleAdapter.notifyDataSetChanged();
                            }
                            if (brands!=null &&brands.size()>0){
                                mBrandsList.clear();
                                mBrandsList.addAll(brands);
                            }
                        }else {

                            ToastUtils.makeText("没有更多数据了");
                        }
                    }

                    @Override
                    protected void _onError(String message) {
                        mYrecycleviewActivityClassifyList.setloadMoreComplete();
                        ToastUtils.makeText(message);

                    }
                },"",lifecycleSubject,false,true);






            }
        });

    }

    @OnClick(R.id.iv_back_activity_class_goods_list)
    public void onMIvBackActivityClassGoodsListClicked() {
        finish();
    }

    @OnClick(R.id.iv_cart_activity_class_goods_list)
    public void onMIvCartActivityClassGoodsListClicked() {
        if (BaseApplication.isLoginSuccess){
            ShopCarActivity.startActivity(this);
        }else {
            LoginActivity.startActivity(this,true);
        }
    }

    @OnClick(R.id.ll_brand_activity_classify_goods_list)
    public void onLlBrandActivityClassGoodsListClicked() {
        if (mBrandsList.size()>0){
        if (mBrandSelectPopuWindow == null) {
            mBrandSelectPopuWindow = new BrandSelectPopuWindow(this);
            mBrandSelectPopuWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    mIvBrandActivityClassifyGoodsList.setImageResource(R.mipmap.down_one);
                    mTvBrandActivityClassifyGoodsList.setTextColor(UIUtils.getColor(R.color.c_ff383838));
                }
            });
        }
        mBrandSelectPopuWindow.setList(mBrandsList,selectBrandList);
        mBrandSelectPopuWindow.showAsDropDown(viewLine2);

        mTvBrandActivityClassifyGoodsList.setTextColor(UIUtils.getColor(R.color.c_29CE7E));
        mIvBrandActivityClassifyGoodsList.setImageResource(R.mipmap.up_green);
        }else {
            ToastUtils.makeText("该商品没有品牌");
        }

    }
    @Subscribe(threadMode = ThreadMode.MAIN)
public void BrandPopuEvent(SelectBrandEvent selectBrandEvent){
        mIvBrandActivityClassifyGoodsList.setImageResource(R.mipmap.direction_default);
        mTvBrandActivityClassifyGoodsList.setTextColor(UIUtils.getColor(R.color.c_ff383838));
        List<Integer> integerList = selectBrandEvent.getIntegerList();
        selectBrandList.clear();

        if (integerList!=null &&integerList.size()>0){
            selectBrandList.addAll(integerList);
           // retry();
        }

        filterQuestionData();
    }

    /**
     * 筛选请求数据
     */
    private void filterQuestionData() {
        currentPosion=1;
        Observable<StatusCode<ClassifyGoodsListBean>> statusCodeObservable = ApiUtils.getApi().getClassifyGoodsLsit(mClassId, selectBrandList, salesSort, priceSort, BaseApplication.getToken(), Contans.rows, currentPosion,BaseApplication.getUserId(),specialSalesType,goodsName)
                .subscribeOn(Schedulers.io()).doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        if (mLoadingDialog == null) {

                            mLoadingDialog = LoadingDialogUtils.createLoadingDialog(ClassifyGoodsListActivity.this, "");
                        }
                        mLoadingDialog.show();
                    }
                }).subscribeOn(AndroidSchedulers.mainThread());

        HttpUtil.getInstance().toSubscribe(statusCodeObservable, new ProgressSubscriber<ClassifyGoodsListBean>(this) {
            @Override
            protected void _onNext(StatusCode<ClassifyGoodsListBean> classifyGoodsListBeanStatusCode) {
                LoadingDialogUtils.closeDialog(mLoadingDialog);
                ClassifyGoodsListBean data = classifyGoodsListBeanStatusCode.getData();
                
                if (classifyGoodsListBeanStatusCode.isFlag()&&data!=null){
                    List<Brands> brands = data.getBrands();
                    List<Goods> goods = data.getGoods();
                    if (goods!=null &&goods.size()>0){
                        showData( true);
                        mGoodsList.clear();
                        mGoodsList.addAll(goods);
                        mClassifyGoodsRecycleAdapter.notifyDataSetChanged();
                    }else {
                        showData( false);
                    }
                    if (brands!=null &&brands.size()>0){
                        mBrandsList.clear();
                        mBrandsList.addAll(brands);
                    }
                }else {
                    showData( false);
                }
            }

            @Override
            protected void _onError(String message) {
                LoadingDialogUtils.closeDialog(mLoadingDialog);
                ToastUtils.makeText(message);
                showData( false);



            }
        },"",lifecycleSubject,false,true);
    }
    @OnClick(R.id.tv_sales_activity_classify_goods_list)
    public void onMTvSalesActivityClassifyGoodsListClicked() {
        if (StringUtils.isEmpty(salesSort)){
            mTvPriceLlPricatrootActivityClassifyGoodsList.setTextColor(UIUtils.getColor(R.color.c_ff383838));
            mTvhouseDirect.setTextColor(UIUtils.getColor(R.color.c_ff383838));
            mIvPriceLlPricatrootActivityClassifyGoodsList.setImageResource(R.mipmap.direction_default);
            priceSort="";
            mTvSalesActivityClassifyGoodsList.setTextColor(UIUtils.getColor(R.color.c_29CE7E));
            salesSort="desc";
            specialSalesType="";
             filterQuestionData();
        }

    }

    @OnClick(R.id.ll_pricatroot_activity_classify_goods_list)
    public void onMLlPricatrootActivityClassifyGoodsListClicked() {
        salesSort="";
        specialSalesType="";
        mTvSalesActivityClassifyGoodsList.setTextColor(UIUtils.getColor(R.color.c_ff383838));
        mTvhouseDirect.setTextColor(UIUtils.getColor(R.color.c_ff383838));
        if (StringUtils.isEmpty(priceSort)){
            mIvPriceLlPricatrootActivityClassifyGoodsList.setImageResource(R.mipmap.direction_down);
            mTvPriceLlPricatrootActivityClassifyGoodsList.setTextColor(UIUtils.getColor(R.color.c_29CE7E));
            //降
            priceSort="desc";
        }else if (priceSort.equals("desc")){
            //升
            priceSort="asc";
            mTvPriceLlPricatrootActivityClassifyGoodsList.setTextColor(UIUtils.getColor(R.color.c_29CE7E));
            mIvPriceLlPricatrootActivityClassifyGoodsList.setImageResource(R.mipmap.direction_up);

        }else if (priceSort.equals("asc")){
            //降
            priceSort="desc";
            mTvPriceLlPricatrootActivityClassifyGoodsList.setTextColor(UIUtils.getColor(R.color.c_29CE7E));
            mIvPriceLlPricatrootActivityClassifyGoodsList.setImageResource(R.mipmap.direction_down);
        }


        filterQuestionData();


    }

    @OnClick(R.id.tv_house_direct_activity_classify_goods_list)
    public void houseDirectOnClice(){
        //业主直供
        specialSalesType="1";
        salesSort="";
        priceSort="";
        mTvSalesActivityClassifyGoodsList.setTextColor(UIUtils.getColor(R.color.c_383838));
        mTvhouseDirect.setTextColor(UIUtils.getColor(R.color.c_29CE7E));


        mTvPriceLlPricatrootActivityClassifyGoodsList.setTextColor(UIUtils.getColor(R.color.c_383838));
        mIvPriceLlPricatrootActivityClassifyGoodsList.setImageResource(R.mipmap.direction_default);




        filterQuestionData();




    }
    @OnClick(R.id.rl_searchcontent_root_activity_classify_goods_list)
    public void gotoSearch(){
        SearchGoodsActivity.startActivity(this);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
